<?php
/**
 * True Gallery Component for Joomla CMS
 *
 * @version 2.5
 * @author Alexey N. Brin (userxp@joomlaportal.ru)
 * @homepage http://truegallery.ru 
 * @filename class.true.php
 * @package True Gallery
 * @copyright (C) 2008-2009 by joomlatune.ru
 * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
 * 
 * THIS GALLERY is an EVOLUTION of AkoGallery -> PonyGallery -> DatsoGallery
 *
 * If you fork this to create your own project, 
 * please make a reference to True Gallery someplace in your code 
 * and provide a link to http://www.joomlatune.ru
 *
 **/

defined('_VALID_MOS') or defined('_JEXEC') or die('Direct Access to this location is not allowed.');

class JTrueGalleryPicture extends JTuneTable
{
	var $id					= null;
	var $catid				= null;
	var $imgtitle			= null;
	var $alias				= null;
	var $imgauthor			= null;
	var $imgtext			= null;
	var $imgdate			= null;
	var $published			= 0;
	var $ordering			= 0;
	var $imgfilename		= null;
	var $imgpath			= null;
	var $width				= 0;
	var $height				= 0;
	var $filesize			= 0;
	var $checked_out		= 0;
	var $owner				= 62;
	var $approved			= null;
	var $useruploaded		= 0;
	var $field1				= null;
	var $field2				= null;
	var $field3				= null;
	var $field4				= null;
	var $field5				= null;
	var $hits				= 0;
	var $metadesc			= null;
	var $metakey			= null;
	var $tags				= null;	

	// cat addon (excluded in store)
	var $cat_name			= null;
	var $cat_alias			= null;

	//function JTrueGalleryPicture( &$db ) {
	function JTrueGalleryPicture() {
		$db = &getDBO();
		parent::__construct( TG_TBLPREFIX, 'id', $db);
	}
	
	function dgMove($id, $catid) {
		global $database, $my;
		if(!(is_array($id)) || (count($id) < 1)) {
			echo "<script> alert('" . _SELECT_ITEM_MOVE . " ); window.history.go(-1);</script>\n";
			return false;
		}
		$ids = implode(',', $id);
		//Перемещаем файлы изображений
		$database->setQuery("SELECT catid, imgfilename FROM ".TG_TBLPREFIX." WHERE id IN ( $ids )");
		$list = $database->loadObjectList();
		//global $mosConfig_absolute_path;
		//require_once (TRUE_ADMIN . "config.true.php");
		//$ad_paththumbs = $ad_path.'/thumbs';
		//$ad_pathimages = $ad_path.'/pictures';
		//$ad_pathoriginals = $ad_path.'/originals';
		foreach($list as $img) {
			$orgimg1 = TG_ORIGINALSPATH.$img->catid.DSX.$img->imgfilename;
			$newimg1 = TG_ORIGINALSPATH.$catid.DSX.$img->imgfilename;
			$orgimg2 = TG_PICTURESPATH.$img->catid.DSX.$img->imgfilename;
			$newimg2 = TG_PICTURESPATH.$catid.DSX.$img->imgfilename;
			$orgimg3 = TG_THUMBSPATH.$img->catid.DSX.$img->imgfilename;
			$newimg3 = TG_THUMBSPATH.$catid.DSX.$img->imgfilename;
			rename($orgimg1, $newimg1);
			rename($orgimg2, $newimg2);
			rename($orgimg3, $newimg3);
		}
		//запрос на обновление строк картинок
		$database->setQuery( "UPDATE ".TG_TBLPREFIX." SET catid='$catid' WHERE id IN ( $ids )" );

		if(!$database->query()) {
			echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
			return false;
		}
		return true;
	} //dgMove
	
	// I DO WANT to use TWO tables!!! :-P
	function load( $oid=null ) {
		$k = $this->_tbl_key;

		if ($oid !== null) {
			$this->$k = $oid;
		}

		$oid = $this->$k;

		if ($oid === null) {
			return false;
		}
		$this->reset();

		$db = &getDBO();

		$query = '
			SELECT a.*, c.name AS cat_name, c.alias AS cat_alias
			FROM '.$this->_tbl.' AS a LEFT JOIN '.TG_TBLPREFIX.'_catg AS c ON c.cid=a.catid
			WHERE a.'.$this->_tbl_key.'='.$db->Quote($oid);
		$db->setQuery( $query );

		if ($result = $db->loadAssoc( )) {
			return $this->bind($result);
		} else {
			$this->setError( $db->getErrorMsg() );
			return false;
		}
	} //load
	
	function store( $updateNulls=false ) {
		unset( $this->cat_name );
		unset( $this->cat_alias );
		return parent::store( $updateNulls );
	} //store
	
	// unfinished
	function getSrc($size=2) {
		$src = '/'.$this->imgfilename;
		$catid = $this->catid ? $this->catid : getUrlParam('cid', 0 );
		if( $this->imgpath ) {
			$w = str_replace( '\\', '/', JPATH_ROOT );// stupid slashes :(
			$src = explode($w.'/',$this->imgpath);
			if( count($src) > 1 ) $src = $src[1];
			else $src = $src[0];
			$src = JTuneConfig::buildPath('front','way') . str_replace('originals','thumbs',$src) . $this->imgfilename;
		} else {
			$src = $catid.$src;
			switch( $size ) {
				case 0: 
					$src = TG_ORIGINALSWAY.$src;
				break;
				
				case 1:
					$src = TG_PICTURESWAY.$src;
				break;
				
				case 2:
					$src = TG_THUMBSWAY.$src;
				break;
				
				default:
				
				break;
			}
		}
		
		$src = str_replace( '\\','/', $src );
		$src = str_replace( '//','/', $src );
		return $src;
	} //getSrc
	
	function buildAjaxLink( $id=0, $catid=0, $Itemid=0, $size=0, $filename='' ) {
		$catid	= intval($catid ? $catid : getUrlParam( 'catid', 0 ));
		$Itemid	= intval($Itemid ? $Itemid : getUrlParam( 'Itemid', 0 ));
		$src = '';
		// undone
		return $src;
	} //buildAjaxLink
}
//
class JTGPicture extends JTrueGalleryPicture{}
//


class JTrueGalleryCategory extends JTuneTable
{
	var $cid			= null;
	var $name			= null;
	var $alias			= null;
	var $description	= '';
	var $desc_full		= '';
	var $parent			= 0;
	var $published		= 0;
	var $ordering		= null;
	var $access			= null;
	var $cmetadesc		= '';
	var $cmetakey		= '';
	var $catimg			= null;
	var $usercat		= null;

	//function JTrueGalleryCategory( &$db ) {
	function JTrueGalleryCategory() {
		$db = &getDBO();
		parent::__construct( TG_TBLPREFIX.'_catg', 'cid', $db );
	}

	function check() {
		$this->cid = intval($this->cid);
		if( $this->cid === 0 ) { unset( $this->cid ); }
		if( !$this->alias ) {
			// encodes russian letters into english.
			// gotta problems with other languages :)
			$this->alias = encoder($this->alias);
		}
		return true;
	}
}
//
class JTGCategory extends JTrueGalleryCategory{}
//

class JTrueGalleryCategoriesHelper
{
	var $__container = null;
	var $__query = null;
	
	function &getInstance() {
		static $i;
		if( !isset( $i ) ) {
			$i = new JTrueGalleryCategoriesHelper();
			//$i->__init();
		}
		return $i;
	}
	
	function __construct() {
		// creating SQL Query object
		$this->__query = new JTuneQuery(); // J1.6 style
		$qry = &$this->__query;
		$qry->select(array('cid','parent','name','alias','published','access'));
		$qry->from(TG_TBLPREFIX.'_catg');
		$qry->order(array('parent','ordering'));
		
		$this->__container = array();
	}
	
	function load() {
		$cont = &$this->getContainer();
		
		
		// это надо бы закэшировать, хотя... 
		// по идее, - это простой запрос в БД, 
		// может пусть сам MySQL кэширует?
		$db = &getDBO();
		$db->setQuery( $this->getQuery() );
		$cont = $db->loadObjectList('cid');
		//
		
		
		// TEMPORARY. FOT TEST ONLY!
		//$rows = array_keys( $cont );
		//foreach( $rows as $cid ) {
			//xdump( $this->getLay( $cid, true, ',', 0 ) );
		//	xdump( $this->getLay( $cid ) );
		//}
		// ***

	}
	
	function getQuery(){
		return $this->__query->__toString();
	}
	
	function &getContainer() {
		return $this->__container;
	}
	
	// очень упрощенная версия построителя path finder-а для категории
	function getLay( $srid, $dir=true, $splitter=null, $top=0, $refresh=false ) {
		// getting categories container
		$cnt = &$this->getContainer();
		$catid = $srid;
		// 
		if( isset($cnt[$catid]->_path ) && !$refresh ) return $cnt[$catid]->_path;
		
		// final result
		$result = array();
		
		// preserving the loop from unwanted cycling
		$count = count( $cnt );
		
		// loop for searching 'path' of categories
		while( isset($cnt[$srid]) && $count>0 && $srid!==$top ){
			
			// straight order
			$result[$srid] = $srid;
			
			// getting next parent
			$srid = $cnt[$srid]->parent;
			
			// decrementing counter
			$count--;
		}
		
		// adding top index
		$result[$srid] = $top;
		
		// reversing order if wanted
		if( !$dir ) $result = array_reverse( $result, true );
		
		// if splitter is not empty then returning string value
		if( $splitter ) $result = implode( $splitter, $result );
		
		// storing path into container
		$cnt[$catid]->_path = $result;
		
		// resetting current position in category's container
		reset( $cnt );
		
		return $cnt[$catid]->_path;
	}
}


/********************************************************/
// aliases for old call compatibility
//class mostrue extends JTrueGalleryPicture{}
//class mosCatgs extends JTrueGalleryCategory{}
/********************************************************/


// unused ???
class JTrueGalleryImagesHelper
{
	var $structure	= null;
	var $acceptables = null;
	
	function &getInstance() {
		static $instance;
		if( !isset( $instance )  ) {
			$instance = &JTrueGalleryImagesHelper::_();
		}
		return $instance;
	}
	
	function &_(){
		$cache	= &JTuneCache::getCache(TG_CMP);
		$cache->setCaching(true);
		$result = &$cache->call( create_function( '', 'return new JTrueGalleryImagesHelper();' ) );
		return $result;
	}
	
	function JTrueGalleryImagesHelper() {
		$this->_load();
	}
	
	function _load( $order = 'ASC' ) {
		$db = &getDBO();
		$db->setQuery( '
			SELECT 
				c.cid, c.parent, c.ordering AS catorder, c.published AS cpub,
				a.id AS imgid, a.ordering AS imgorder, a.published AS apub, a.approved, a.checked_out,
				u1.id AS catuserid, u1.name AS catuserlogin, u1.username AS catusername,
				u2.id AS imguserid, u2.name AS imguserlogin, u2.username AS imgusername
			FROM '.TG_TBLPREFIX.'_catg AS c 
				LEFT JOIN '.TG_TBLPREFIX.' AS a ON a.catid=c.cid
				LEFT JOIN #__users AS u1 ON c.access=u1.id
				LEFT JOIN #__users AS u2 ON a.owner=u2.id
			ORDER BY c.cid ASC, c.ordering '.$order.', a.ordering '.$order
		); 
		// WHERE a.published=1 AND c.published=1
		
		if( !($cur = $db->query()) ) {
			return null;
		}
		
		$array = array();
		
		$iorder = 0;
		while( $row = mysql_fetch_object( $cur )) {
			$array[$row->cid]['cid']		= $row->cid;
			$array[$row->cid]['pid']		= $row->parent;
			$array[$row->cid]['pub']		= $row->cpub;
			$array[$row->cid]['ord']		= $row->catorder;
			$array[$row->cid]['uid']		= $row->catuserid;
			//$array[$row->cid]['catuserlogin']	= $row->catuserlogin;
			//$array[$row->cid]['catusername']	= $row->catusername;
			
			if( !isset( $array[$row->cid]['tim'] ) ) {
				$array[$row->cid]['tim'] = 0;
				$array[$row->cid]['ims'] = array();
				$array[$row->cid]['imo'] = array();
				$imgorder = 0;
			}
			
			if( $row->imgid ) {
				// нужно ли осуществлять проверку на показ сразу при загрузке массива???
				// если вызов кэшировать, то это может работать необычным образом
				// может, кэшировать только вызов к БД???
				// тогда потом можно будет проще делать навигацию
				
				// проверяем плагином можно ли переходить на эту картинку или нет
				if( $this->__approve( $row ) ) {
					$array[$row->cid]['tim']++;
					$array[$row->cid]['ims'][$row->imgid]['id']			= $row->imgid;
					$array[$row->cid]['ims'][$row->imgid]['ipub']		= $row->apub;
					//$array[$row->cid]['ims'][$row->imgid]['iord']		= $row->imgorder;
					$array[$row->cid]['ims'][$row->imgid]['iord']		= $imgorder;
					$array[$row->cid]['ims'][$row->imgid]['iuid']		= $row->imguserid;
					$array[$row->cid]['ims'][$row->imgid]['iapp']		= $row->approved;
					$array[$row->cid]['ims'][$row->imgid]['icho']		= $row->checked_out;
					//$array[$row->cid]['ims'][$row->imgid]['iulg']	= $row->imguserlogin;
					//$array[$row->cid]['ims'][$row->imgid]['iunm']		= $row->imgusername;
					
					$array[$row->cid]['imo'][$imgorder] = $row->imgid;
					$imgorder++;
				}
			}
		}
		mysql_free_result( $cur );
		
		$this->structure = $array;
	} //_load
	
	function getImagesId( $imgid='' ) {
		
		// найти категорию изображения
		$cid = $this->findcatid( $imgid );
		//xdump( $cid, 'CID: ' );
		if( $cid=='' ) return null;
		
		//xdump( $this->structure[$cid], 'IMAGES: ' );
		
		// позиция текущего изображения
		$current	= $this->structure[$cid]['ims'][$imgid]['iord'];
		//xdump( $current, 'CURRENT: ' );
		
		//xdump( $this->structure[$cid]['imo'], '===' );
		
		// последний индекс массива
		$first	= 0;
		$last	= $this->structure[$cid]['tim']-1; // total images - 1
		//xdump( $last, 'LAST ' );
		
		// id текущего изображения
		$result->current = $imgid;
		
		// получить id предыдущего изображения
		$result->prev = $current > $first ? $this->structure[$cid]['imo'][$current-1] : '';
		
		// получить id следующего изображения
		$result->next = $current < $last ? $this->structure[$cid]['imo'][$current+1] : '';
		
		// получить id предыдущего изображения
		$result->first = $current != $first ? $this->structure[$cid]['imo'][$first] : '';
		
		// получить id следующего изображения
		$result->last = $current != $last ? $this->structure[$cid]['imo'][$last] : '';
		
		return $result;
		
	} //getImagesId
	
	function findcatid( $imgid='' ) {
		
		$cid = '';
		$structure = &$this->structure;
		
		foreach( $structure as $cat ) {
			$imgs = array_keys( $cat['ims'] );
			
			if( in_array( $imgid, $imgs ) ) {
				$cid = $cat['cid'];
				break;
			}
		}
		
		return $cid;
		
	} //findcatid
	
	function __approve( &$row ) {
		
		//if image approved
		if( $row->approved===0 ) return false;
		
		//if image published
		if( $row->apub===0 ) return false;
		
		//if user for image allowed
		//$my = &getUser();
		//if( $row->imguserid !== $my->id ) return false;
		
		//if category published
		if( $row->cpub===0 ) return false;
		
		//if user for category allowed
		
		return true;
		
	} //__approve
	
} //JTrueGalleryImagesHelper

class JTrueGalleryHelper
{
	function _geCatsTree() {
		$db = &getDBO();
		$tbl = TG_TBLPREFIX.'_catg';
		
		/*
		$mt = getmicrotime();
		$sql = "SELECT GROUP_CONCAT(CONCAT(cid,'=>array(',cid,',',parent,',',ordering,')')) FROM ".$tbl;
		$db->setQuery( $sql );
		$res = $db->loadRow();
		if( !count( $res ) ) {
			$res[0] = $res[1] = '';
		}
		eval( '$rows	=array('.$res[0].');' ); // идентификаторы категорий
		$sort = array();
		foreach( $rows as $row ) {
			$sort[$row[0]] = $row[2].'-'.$row[0];
			$key = $row[1];
			while( isset( $rows[$key][1] ) ) {
				$sort[$row[0]] = $rows[$key][2].'-'.$rows[$key][0].'.'.$sort[$row[0]];
				$key = $rows[$key][1];
			}
		}
		natsort( $sort );
		xdump( getmicrotime() - $mt );
		*/
		
		// данный способ на 20-30% медленнее, чем ниже следующий
		// и все из-за сложной выборки из БД +
		// обработка вложенных массивов оказывается работает быстрее, 
		// чем прыгание по индексам внутри одного массива, 
		// прямые ссылки на элементы вместо индексации жестоко рулят!!!
		
		//$mt = getmicrotime();
		/*  *************************************  */
		$abcd	= array();
		$chains	= array();
		$subcats = array();
		
		$db->setQuery( 'SELECT `cid`,`parent`,`ordering` FROM '.$tbl.' ORDER BY ordering' );
		if( $cur = $db->query() ) {
			// indexed array is little bit faster than objected
			while( $row = mysql_fetch_row( $cur ) ) {
				$abcd[$row[0]][0]	= $row[0]; // cid
				$abcd[$row[0]][1]	= $row[2]; // ordering
				
				$row[1] = $row[0] == $row[1] ? 0 : $row[1]; // preventing when PARENT == ID
				
				$abcd[$row[1]][0]	= $row[1]; // parent
				$abcd[$row[0]][2]	=&$abcd[$row[1]]; // link to parent
			}
		}
		mysql_free_result( $cur );
		foreach( $abcd as $row ) {
			if( isset( $row[2] ) ) {
				$a = &$row[2];
				$chains[$row[0]] = $row[1].'-'.$row[0].'.';
				
				$count=100;
				while( isset( $a[2] ) && $count >0 && $a[0] !== 0 ) {
					$chains[$row[0]] = $a[1].'-'.$a[0].'.'.$chains[$row[0]];
					$a = &$a[2];
					$count--;
				}
		
				$p = &$row[2][0];
				if( isset( $subcats[$p] ) ) $subcats[$p]++;
				else $subcats[$p] = 1;
			}
		}
		natsort( $chains );
		
		$sql = '
			SELECT c.cid, c.parent, c.name, c.description, c.ordering, c.published, 
			c.access, c.cmetadesc, c.cmetakey, g.name AS groupname, COUNT(i.id) AS imgcnt, 0 AS subcats
			FROM '.TG_TBLPREFIX.'_catg AS c
				LEFT JOIN '.TG_TBLPREFIX.' AS i ON i.catid=c.cid
				LEFT JOIN #__groups g ON g.id = c.access 
			GROUP BY cid
			ORDER BY c.ordering, c.parent, c.name
		';
		$db->setQuery( $sql );
		$abcd = $db->loadObjectList( 'cid' );
		
		$rows = array();
		foreach( $chains as $cid=>$chain ) {
			$rows[$cid] = $abcd[$cid];
			$rows[$cid]->level = substr_count($chain, '.');
			$rows[$cid]->subcats = isset( $subcats[$cid] ) ? $subcats[$cid] : 0;
		}
		$rows[0]->subcats = isset( $subcats[0] ) ? $subcats[0] : 0;
		
		return $rows;
	} //_geCatsTree
	
	function getNaviCats( $cid=null ) {
		$db = &getDBO();
		$db->setQuery( 'SELECT `cid`,`parent`,`name` FROM '.TG_TBLPREFIX.'_catg' );
		$rows = $db->loadRowList(0);
		
		if( $cid ) {
			$cid = intval( $cid );
			$path = array();
			while( isset( $rows[$cid] ) ) {
				array_unshift($path, $rows[$cid]);
				$cid = $rows[$cid][1];
			}
			return $path;
		} else {
			return null;
		}
	} //getNaviCats
	
	//Сохранение языкового файла
	function saveLanguage($option) {
		global $language;

		$file = JTInput::getParam ( $_POST, 'file', '' );
		$filecontent = JTInput::getParam ( $_POST, 'filecontent', '', 4 );

		if (! $filecontent) {
			JTuneRouter::_ ( "index2.php?option=$option&task=settings", JText::_ ( 'TG_LANG_EMPTY' ) );
		}
		if (file_exists ( TRUE_BASE . 'languages' . DS . $language->getLanguage () . '.ini' )) {
			$file = TRUE_BASE . 'languages' . DS . $language->getLanguage () . '.ini';
		} else {
			$file = TRUE_BASE . 'languages' . DS . 'english.ini';
		}
		$enable_write = JTInput::getParam ( $_POST, 'enable_write', 0 );
		$oldperms = fileperms ( $file );
		if ($enable_write)
			@chmod ( $file, $oldperms | 0222 );
		clearstatcache ();
		if (is_writable ( $file ) == false) {
			JTuneRouter::_ ( "index2.php?option=$option&task=settings", JText::_ ( 'TG_LANG_IS_NOT_WRITEABLE' ) );
		}
		if ($fp = fopen ( $file, "w" )) {
			fputs ( $fp, stripslashes ( $filecontent ) );
			fclose ( $fp );
			if ($enable_write) {
				@chmod ( $file, $oldperms );
			} else {
				if (mosGetParam ( $_POST, 'disable_write', 0 ))
					@chmod ( $file, $oldperms & 0755 );
			}
			JTuneRouter::_ ( "index2.php?option=$option&task=settings", JText::_ ( 'TG_LANG_SAVED' ) );
		} else {
			if ($enable_write)
				@chmod ( $file, $oldperms );
			JTuneRouter::_ ( "index2.php?option=$option", JText::_ ( 'TG_LANG_IS_NOT_WRITEABLE' ) );
		}
	}
	
	function uploadhandler() {
		// getting components config parameters
		$pars = &JTuneConfig::getParameters();
		extract( $pars ); // может этот как-то по другому лучше сделать?
		
		$imagetype = array (1 => 'GIF', 2 => 'JPG', 3 => 'PNG' );
		$imginfo = getimagesize( $org_screenshot );
		if ($imginfo [0] = 0) {
			JTuneRouter::_( TRUE_INDEX2.'&view=upload', _DG_FILENAME_BAD_UPLOAD );
			exit ();
		}
		$imginfo [2] = $imagetype[$imginfo [2]];
		if ($imginfo [2] != 'GIF' && $imginfo [2] != 'JPG' && $imginfo [2] != 'PNG') {
			JTuneRouter::_ ( TRUE_INDEX2.'&view=upload', _DG_FILENAME_BAD );
			exit ();
		}
		
		$catid = getUrlParam( 'catid', '' ); // MINE :)
		$org_screenshot_name = dgImgId( $catid, $imginfo [2] );

		// do i need to fix it???
		$org_screenshot 	= @$_FILES['org_screenshot']['tmp_name'];
		
		if( $org_screenshot && $ad_orgresize ) {
			if( strlen ( $org_screenshot_name ) > 0 and $org_screenshot_name != 'none' ) {
				$img_info = getimagesize( $org_screenshot );
				if( $img_info [0] > $ad_orgwidth or $img_info [1] > $ad_orgheight ) {
					dgImageCreate( $org_screenshot, TG_ORIGINALSPATH . $org_screenshot_name, $ad_orgwidth, $ad_orgheight, $ad_thumbquality, "1" );
				} else {
					copy( $org_screenshot, TG_ORIGINALSPATH . $org_screenshot_name );
					chmod( TG_ORIGINALSPATH . $org_screenshot_name, 0644);
				}
			}
		}
		
		// original picture
		if( !$ad_orgresize ) {
			if (strlen ( $org_screenshot ) > 0 and $org_screenshot != 'none') {
				copy ( $org_screenshot, TG_ORIGINALSPATH . $org_screenshot_name );
				chmod( TG_ORIGINALSPATH . $org_screenshot_name, 0644);
			}
		}
		
		// middlesize thumbnail
		if( $imginfo [0] > $ad_maxwidth or $imginfo [1] > $ad_maxheight ) {
			dgImageCreate ( $org_screenshot, TG_PICTURESPATH . $org_screenshot_name, $ad_maxwidth, $ad_maxheight, $ad_thumbquality, "1" );
		} else {
			copy ( $org_screenshot, TG_PICTURESPATH . $org_screenshot_name );
			chmod( TG_PICTURESPATH . $org_screenshot_name, 0644);
		}
		
		// small thumbnail
		if( $thumbcreation ) {
			dgImageCreate ( $org_screenshot, TG_THUMBSPATH . $org_screenshot_name, $ad_thumbwidth, $ad_thumbheight, $ad_thumbquality, $ad_crsc );
			chmod( TG_THUMBSPATH . $org_screenshot_name, 0644);
		}
		
		$db = & getDBO ();
		$db->setQuery ( 'SELECT ordering FROM #__true WHERE catid='.$catid.' ORDER BY ordering DESC LIMIT 1' );

		$ordering1	= $db->loadResult ();
		$ordering	= $ordering1 + 1;
		
		$imgdate = mktime();
		$db->setQuery("
			INSERT INTO #__true(
				catid, imgtitle, imgauthor, imgtext, imgdate, ordering, imgvotes, imgvotesum, 
				published, imgfilename, checked_out, owner, approved,
				field1, field2, field3, field4, field5, metadesc, metakey, tags)
			VALUES(
				'$catid', '$imgtitle', '$imgauthor', '$imgtext', '$imgdate', '$ordering', '0', '0',
				'1','$org_screenshot_name', '0',
				'$my->id', 1,'$field1', '$field2', '$field3', '$field4', '$field5', '', '', '$tags')
		");
		
		if( !$db->query() ) {
			echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
			exit ();
		}
		
		//пишем в счетчик
		$last_id = $db->insertid ();
		$db->setQuery ( "INSERT INTO #__true_count(id, imgid, count) VALUES (NULL, '$last_id', '0')" );
		$db->query ();
		
		JTuneRouter::_ ( TRUE_INDEX2.'&view=pictures' );
	} //uploadhandler

	function batchuploadhandler() {
		// getting components config parameters
		$pars = &JTuneConfig::getParameters();
		extract( $pars );
		
		//$temp_dir = str_replace( '\\', '/', JPATH_ROOT . DSX .'media' );
		$catid = getUrlParam( 'catid', '' );
		require_once( JPATH_BASE.DSX.'includes'.DSX.'pcl'.DSX.'pclzip.lib.php');
		
		//if ($zippack_type !== 'application/zip'){
		//JTuneRouter::_( "TRUE_INDEX2.'&view=pictures", "FILE IS NOT A ZIP PACKAGE" );
		//}
		
		$zipfile = new PclZip( $_FILES['zippack']['tmp_name'] );
		$ziplist = $zipfile->listContent();
		//$zipfile->extract( $temp_dir );
		$zipfile->extract( TG_MEDIA );
		
		$db = & getDBO ();
		
		//xdump( $catid, 'CATEGORY: ' );
		//xdump( $ziplist, 'ZIPLIST: ' );
		
		for( $i = 0; $i < sizeof ( $ziplist ); $i ++ ) {
			
			$origfilename = $ziplist[$i]['filename'];
			$imagetype = array (1 => 'GIF', 2 => 'JPG', 3 => 'PNG' );
			
			//$original_file = $temp_dir . DSX . $origfilename;
			$original_file = TG_MEDIA . DSX . $origfilename;
			//xdump( $original_file, 'ORIGINAL file: ' );
			
			$imginfo = getimagesize( $original_file );
			if( $imginfo[0] = 0 ) {
				JTuneRouter::_( TRUE_INDEX2.'&view=upload', _DG_FILENAME_BAD_UPLOAD );
				exit();
			}			
			$imginfo[2]		= $imagetype[$imginfo[2]];
			$compacttitle	= strtolower( str_replace ( ' ', '', $gentitle ) );
			
			$newfilename	= dgImgId( $catid, $imginfo[2] );
			$newfilename_op = TG_ORIGINALSPATH	. $catid . DSX . $newfilename;
			
			if( $ad_orgresize ) {
				$img_info = getimagesize( $original_file );
				if( $img_info [0] > $ad_orgwidth || $img_info [1] > $origfilename ) {
					dgImageCreate( $original_file, $newfilename_op, $ad_orgwidth, $ad_orgheight, $ad_thumbquality, '1' );
				} else {
					copy( $original_file, $newfilename_op );
					chmod( $newfilename_op, 0644 );
				}
			}
			
			if( !$ad_orgresize ) {
				copy( $original_file, $newfilename_op );
				chmod( $newfilename_op, 0644);
			}
			
			dgImageCreate( $original_file, TG_PICTURESPATH . $catid . DSX . $newfilename, $ad_maxwidth,   $ad_maxheight,   $ad_thumbquality, '1' );
			dgImageCreate( $original_file, TG_THUMBSPATH . $catid . DSX . $newfilename, $ad_thumbwidth, $ad_thumbheight, $ad_thumbquality, $ad_crsc );
			
			chmod( TG_PICTURESPATH . $catid . DSX . $newfilename, 0644);
			chmod( TG_THUMBSPATH . $catid . DSX . $newfilename, 0644);
			
			//unlink ( $p_path = $original_file );
			unlink( $original_file );
			
			$batchtime = mktime ();
			$db->setQuery( "SELECT ordering FROM #__true WHERE catid=$catid ORDER BY ordering DESC LIMIT 1" );
			$ordering1 = $db->loadResult();
			$ordering = $ordering1 + 1;
			
			$db->setQuery("
				INSERT INTO #__true(
					catid, imgtitle, imgauthor, imgtext, imgdate, ordering, imgvotes, imgvotesum, 
					published, imgfilename,checked_out, owner, 
					approved, field1, field2, field3, field4, field5, metadesc, metakey, tags)
				VALUES(
					'$catid', '$gentitle $i', '$photocred', '$gendesc', '$batchtime', '$ordering', 
					'0', '0', '1', '$newfilename', '0', '$my->id', 1, 
					'$field1', '$field2', '$field3', '$field4', '$field5', '', '', '$tags')
			");
			if( !$db->query() ) {
				echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
				exit ();
			}
			
			// не нравится мне вот это ниже :)
			//пишем в счетчик
			$last_id = $db->insertid ();
			$db->setQuery( "INSERT INTO #__true_count(imgid, count) VALUES('$last_id', '0')" );
			$db->query();
		}
		
		$picsadded = count( $ziplist );
		
		//JTuneRouter::_( TRUE_INDEX2.'&view=pictures', JText::_( 'TG_ADDED_IMAGES' ) . $picsadded );
		echo "<a href=\"".TRUE_INDEX2."&view=pictures\">".JText::_( 'TG_ADDED_IMAGES' ) . $picsadded."</a>";

	} // batchuploadhandler
	
	// Функция сохранения настроек
	function saveConfig() {
		$pars		= &JTuneConfig::getParameters();
		$ad_path	= getUrlParam( 'ad_path', '' );
		
		if( $pars['ad_path'] != $ad_path ) {
			$old_ad_path = str_replace( '\\', '/', JTuneConfig::getCfg('absolute_path') . $pars['ad_path'] );
			$new_ad_path = str_replace( '\\', '/', JTuneConfig::getCfg('absolute_path') . $ad_path );
			rename( $old_ad_path, $new_ad_path );
		}

		$set	= '';
		$set2	= '';
		if( isset( $pars['ad_itemid'] ) ) {
			$ad_itemid = $pars['ad_itemid'];
			unset( $pars['ad_itemid'] );
		} else {
			$ad_itemid = 0;
		}
		
		foreach( $pars as $key=>$value ) {
			if( isset( $_POST[$key] ) ) {
				$value = getUrlParam( $key, $value, $_POST );
				$set .= "$key='$value',";
				$set2.= "$key=$value\n";
			}
		}
		$set = "ad_params='$set2',".$set;
		//xdump( $set );
		
		$set = substr( $set, 0, -1 );
		
		$db = &getDBO ();
		$db->setQuery( 'UPDATE '.TG_TBLPREFIX.'_config SET '.$set.' WHERE ad_itemid='.$ad_itemid );
		$db->query();
		
		JTuneRouter::_ ( TRUE_INDEX2.'&view=settings&task=show', JText::_('TG_SETT_SAVED') );
		//echo "<br/>\n".'<a href="'.TRUE_INDEX2.'&task=settings'.'">'.JText::_('TG_SETT_SAVED').'</a>';
	} //saveConfig
	
	// Утверждение картинок
	function approvePicture( $cid = null, $approve = 1 ) {
		$db = & getDBO ();
		if (! is_array ( $cid ) || count ( $cid ) < 1) {
			$action = $approve ? 'approve' : 'reject';
			echo "<script> alert('" . JText::_ ( 'TG_SELECT_AN_ITEM' ) . " $action'); window.history.go(-1);</script>\n";
			exit ();
		}
		$cids = implode( ',', $cid );
		$db->setQuery( 'UPDATE #__true SET approved=\''.$approve.'\' WHERE id IN('.$cids.')' );
		if( !$db->query() ) {
			echo "<script>alert('".$db->getErrorMsg()."'); window.history.go(-1); </script>\n";
			exit ();
		}
		//JTuneRouter::_ ( TRUE_INDEX2 );
	} //approvePicture
	
	// порядок картинок
	function orderPic( $inc ) {
		$db = & getDBO ();
		
		$uid = getUrlParam( 'id', 0 );
		$uid = isset($uid[0]) ? $uid[0] : $uid;
		
		//xdump( $uid );
		
		//// TO DO: ПЕРЕДЕЛАТЬ!!!!
		/*$db->setQuery( "SELECT catid FROM {TG_TBLPREFIX} WHERE id=$uid" );
		$piccatid = $db->loadResult();
		
		$db->setQuery( "SELECT ordering, id FROM {TG_TBLPREFIX} WHERE id=$uid" );
		$result = $db->query();
		
		$id1 = mysql_result( $result, 0, 'id' );
		$ordering1 = mysql_result( $result, 0, 'ordering' );*/
		
		
		$db->setQuery( 'SELECT id, ordering, catid FROM '.TG_TBLPREFIX.' WHERE id='.$uid );
		list( $id1, $ordering1, $piccatid ) = $db->loadRow();
		
		//xdump($id1, 'id: ');
		//xdump($ordering1, 'ordering was: ');
		//xdump($piccatid, 'catid: ');
		//xdump(($inc ? 'up' : 'down'), 'inc: ');
		
		/*
			сбросить/обновить порядок:
			выбрать по порядку все записи в категории, если ordering > -1
			ибо тех, что меньше 0, считаем принудительно торчащими :))))
		*/
		
		/*$sql = 'SELECT id, ordering FROM '.TG_TBLPREFIX.' WHERE catid='.$piccatid.' ORDER BY ordering, imgtitle';
		$db->setQuery( $sql );
		$rows = array();
		if (!($cur = $db->query())) {
			//return null;
		} else {
			while( $row = mysql_fetch_object( $cur ) ) {
				//$rows[$row->id] = $row->id;
				$rows[$row->id] = $row->ordering;
			}
		}
		mysql_free_result( $cur );
		xdump( $rows );*/
		
		if( $inc==1) {
			$dir = 'DESC'; $cond = '<='; $sign='+';
			$sql = 'UPDATE '.TG_TBLPREFIX.' SET ordering=ordering-1 WHERE id='.$id1; // UP
		} else {
			$dir = 'ASC'; $cond = '>='; $sign='-';
			$sql = 'UPDATE '.TG_TBLPREFIX.' SET ordering=ordering+1 WHERE id='.$id1; // DOWN
		}
		$db->setQuery( $sql );
		$db->query();
		//xdump( $db->getQuery() );
		
		//$db->setQuery( 'SELECT id, ordering FROM '.TG_TBLPREFIX.' WHERE catid='.$piccatid.' AND ordering'.$cond.$ordering1.' AND id<>'.$id1.' ORDER BY ordering '.$dir.' LIMIT 1' );
		$sql = '
		UPDATE '.TG_TBLPREFIX.' 
		SET ordering=ordering'.$sign.'1 
		WHERE catid='.$piccatid.' AND ordering'.$cond.$ordering1.' AND id<>'.$id1.' 
		ORDER BY ordering '.$dir.' LIMIT 1
		';
		$db->setQuery( $sql );
		$db->query();
		//xdump( $db->getQuery() );
		
		
		/*$sql = 'UPDATE '.TG_TBLPREFIX.' SET ordering=0 WHERE catid='.$piccatid.' AND ordering>=0 ORDER BY ordering LIMIT 1';
		$db->setQuery( $sql );
		$db->query();
		xdump( $db->getQuery());*/
		
		$db->setQuery( 'SET @r:=0;' );
		$db->query();
		$sql = 'UPDATE '.TG_TBLPREFIX.' SET ordering=(@r:=@r+1) WHERE catid='.$piccatid.' AND ordering>=0 ORDER BY ordering';
		$db->setQuery( $sql );
		$db->query();
		//xdump( $db->getQuery());
		
		
		
		
		//$sql = 'UPDATE '.TG_TBLPREFIX.' SET ordering=0 WHERE catid='.$piccatid;
		//$db->setQuery( $sql );
		
		//if ($inc == 1) {
		//	$db->setQuery( "SELECT ordering, id FROM {TG_TBLPREFIX} WHERE catid=$piccatid and ordering > $ordering1 ORDER BY ordering LIMIT 1" );
		//} else {
		//}
		

		/*
		xdump($id2, 'id2: ');
		xdump($ordering2, 'ordering2: ');
		
		//$result = $db->query();
		//$ordering2 = mysql_result ( $result, 0, 'ordering' );
		//$id2 = mysql_result ( $result, 0, 'id' );
		
		$db->setQuery( 'UPDATE '.TG_TBLPREFIX.' SET ordering='.$ordering1.' WHERE id='.$id2 );
		$result = $db->query();
		
		$db->setQuery( 'UPDATE '.TG_TBLPREFIX.' SET ordering='.$ordering2.' WHERE id='.$id1 );
		$result = $db->query();*/
		
		JTuneRouter::_ ( TRUE_INDEX2 );
		
	} //orderPic
	
	// Функция сохранения порядка картинок
	function saveOrder() {
		$db		= &getDBO();
		$cid	= getUrlParam( 'id', null );
		$total	= count( $cid );
		$order	= josGetArrayInts( 'order' );
		for( $i=0; $i < $total; $i++ ) {
			$query = "UPDATE ".TG_TBLPREFIX." SET ordering = " . (int)$order[$i] . " WHERE id = " . (int)$cid[$i];
			$db->setQuery( $query );
			if( !$db->query() ) {
				echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
				exit();
			}
			$row = new JTrueGalleryPicture( $db );
			$row->load( $cid[$i] );
			//$row->updateOrder(' ');
		}
		JTuneRouter::_( TRUE_INDEX2, JText::_( 'TG_ORDERING_OK' ) );
	} //saveOrder
	
	//Функция публикации картинок
	function publishPicture( $publish = 1 ) {
		$db = & getDBO ();
		
		$cid = getUrlParam( 'cid', null );
		
		if( !is_array( $cid ) || count( $cid ) < 1) {
			$action = $publish ? 'publish' : 'unpublish';
			echo "<script> alert('" . JText::_ ( 'TG_SELECT_AN_ITEM' ) . " $action'); window.history.go(-1);</script>\n";
			exit ();
		}
		$cids = implode( ',', $cid );
		$db->setQuery( "UPDATE #__true SET published='$publish' WHERE id IN ($cids)" );
		if (! $db->query ()) {
			echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
			exit ();
		}
		
		JTuneRouter::_( TRUE_INDEX2 );
		
	} //publishPicture
	
	//Функция удаления картинок
	function removePicture( $cid ) {
		//global $app, $ad_path;
		$pars = &JTuneConfig::getParameters();
		extract( $pars );
		
		$db = & getDBO ();

		if (! is_array ( $cid ) || count ( $cid ) < 1) {
			echo "<script> alert('" . JText::_ ( 'TG_SELECT_ITEM_TO_DELETE' ) . "'); window.history.go(-1);</script>\n";
			exit ();
		}
		if (count ( $cid )) {
			for($i = 0; $i < count ( $cid ); $i ++) {
				$db->setQuery ( "SELECT id, imgfilename, catid FROM #__true WHERE id = $cid[$i]" );
				if ($db->query ()) {
					$rows = $db->loadObjectList ();
					$row = $rows [0];
					$catid = $row->catid;
					//$ad_paththumbs = $ad_path.'/thumbs/';
 					//$ad_pathimages = $ad_path.'/pictures/';
  					//$ad_pathoriginals = $ad_path.'/originals/';
					if (removeFile ( $row->imgfilename, TG_PICTURESPATH, $catid )) {
						if (removeFile ( $row->imgfilename, TG_THUMBSPATH, $catid )) {
							if (! removeFile ( $row->imgfilename, TG_ORIGINALSPATH, $catid )) {
							}
						} else {
							//die(JText::_('TG_NOT_DELETE_THMB_IMAGE_FILE);
						}
					} else {
						//die(JText::_('TG_FFFFFFF);
					}
				} else {
					echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
				}
			}
			$cids = implode ( ',', $cid );
			$db->setQuery ( "DELETE from #__true where id IN ($cids)" );
			if (! $db->query ()) {
				echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
			}
			$db->setQuery ( "DELETE from #__true_count where imgid IN ($cids)" );
			if (! $db->query ()) {
				echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
			}
		}
		$txtmsg = 'pictures successfully removed';
		JTuneRouter::_ ( TRUE_INDEX2, $txtmsg );
	} //removePicture
	
	function publishCategory( $publish = true ) {
		$db = & getDBO ();
		$cid = getUrlParam( 'cid', null );
		
		if( !is_array( $cid ) || count( $cid ) < 1) {
			$action = $publish ? 'publish' : 'unpublish';
			echo "<script> alert('" . JText::_ ( 'TG_SELECT_AN_ITEM' ) . " $action'); window.history.go(-1);</script>\n";
			exit ();
		}
		$cids = implode( ',', $cid );
		$db->setQuery( 'UPDATE '.TG_TBLPREFIX.'_catg SET published=\''.$publish.'\' WHERE id IN ('.$cids.')' );
		if (! $db->query ()) {
			echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
			exit ();
		}
		$txtmsg = 'Selected categories successfully published';
		JTuneRouter::_ ( TRUE_INDEX2.'&view=categories', $txtmsg );
	}
	function removeCategory( $cid ) {
		//$pars = &JTuneConfig::getParameters();
		//extract( $pars );
		
		$db = & getDBO();

		//if( !is_array( $cid ) || sizeof( $cid ) < 1 ) {
		if( !$cid ) {
			echo "<script> alert('" . JText::_ ( 'TG_SELECT_ITEM_TO_DELETE' ) . "'); window.history.go(-1);</script>\n";
			exit();
		}
		if( is_array( $cid ) ) $cid = implode( ',', $cid );
		
		//if( sizeof( $cid ) ) {
			for($i = 0; $i < count ( $cid ); $i ++) {
				$db->setQuery ( "SELECT id, imgfilename, catid FROM #__true WHERE id = $cid[$i]" );
				if ($db->query ()) {
					$rows = $db->loadObjectList ();
					$row = $rows [0];
					$catid = $row->catid;
					//$ad_paththumbs = $ad_path.'/thumbs/';
 					//$ad_pathimages = $ad_path.'/pictures/';
  					//$ad_pathoriginals = $ad_path.'/originals/';
					if (removeFile ( $row->imgfilename, TG_PICTURESPATH, $catid )) {
						if (removeFile ( $row->imgfilename, TG_THUMBSPATH, $catid )) {
							if (! removeFile ( $row->imgfilename, TG_ORIGINALSPATH, $catid )) {
							}
						} else {
							//die(JText::_('TG_NOT_DELETE_THMB_IMAGE_FILE);
						}
					} else {
						//die(JText::_('TG_FFFFFFF);
					}
				} else {
					echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
				}
			}
			$cids = implode ( ',', $cid );
			$db->setQuery ( "DELETE from #__true where id IN ($cids)" );
			if (! $db->query ()) {
				echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
			}
			$db->setQuery ( "DELETE from #__true_count where imgid IN ($cids)" );
			if (! $db->query ()) {
				echo "<script> alert('" . $db->getErrorMsg () . "'); window.history.go(-1); </script>\n";
			}
		//}
		
		
		$txtmsg = 'pictures successfully removed';
		JTuneRouter::_ ( TRUE_INDEX2.'&view=categories', $txtmsg );
	} //removeCategory
	
	//Результат перемещения картинок
	function movePicResult() {
		global $movepic;
		$db		= &getDBO();
		$images	= getUrlParam( 'images', 0 );
		$cid	= getUrlParam( 'cid', 0 );

		xdump( $_POST );
		
		if( !$movepic || $movepic == 0 ) {
			echo "<script> alert('" . JText::_ ( 'TG_MUST_SELECT_CATEGORY' ) . "'); window.history.go(-1);</script>\n";
			//exit();
		}
		else {
			$pic = new JTrueGalleryPicture( $db );
			$pic->dgMove ( $id, $movepic );
			$ids = implode ( ',', $id );
			$imgthumbname = implode ( ',', $imgthumbname1 );
			$total = count ( $id );
			$cat = new mosCatgs ( $db );
			$cat->load ( $movepic );
			$msg = $total . JText::_( 'TG_TOTAL_PICS_MOVED' ) . $cat->name;
			
			
			
			
			//JTuneRouter::_ ( TRUE_INDEX2 . '&task=pictures&mosmsg=' . $msg );
		}
		
	} //movePicResult

	//Установка защиты картинок через .htaccess
	//function dgProtect( $dirtoprotect ){
	function doProtect( $dirtoprotect ){
		//require_once (TRUE_ADMIN . "config.true.php");
		$htaccess = "Order Deny,Allow\nDeny from All";
		$wf = fopen ( JTuneConfig::getCfg ( 'absolute_path' ) . $dirtoprotect . "/.htaccess", "w+" );
		if (! fwrite ( $wf, $htaccess ))
			;
		fclose ( $wf );
	} //doProtect

	//Удаление защиты
	//function dgUnprotect( $dirtounprotect ){
	function unProtect( $dirtounprotect ){
		//require_once (TRUE_ADMIN . 'config.true.php');
		if (file_exists ( JTuneConfig::getCfg ( 'absolute_path' ) . $dirtounprotect . "/.htaccess" )) {
			unlink ( JTuneConfig::getCfg ( 'absolute_path' ) . $dirtounprotect . "/.htaccess" );
		}
	} //unProtect

	//Получает то ли число ссылок то нумерованные списки (снова фигня)
	function getNumberOfLinks( $cat ){
		$db = & getDBO();

		$queue [] = intval ( $cat );
		while ( list ( $key, $cat ) = each ( $queue ) ) {
			$db->setQuery ( "SELECT cid FROM #__true_catg WHERE parent=$cat AND published=1" );
			$result = $db->query ();
			$total = mysql_num_rows ( $result );
			$j = 0;
			while ( $j < $total ) {
				$val = mysql_fetch_row ( $result );
				$queue [] = $val [0];
				$j ++;
			}
		}
		reset ( $queue );
		$query = "SELECT count(*) FROM #__true  WHERE ( 0!=0";
		while ( list ( $key, $cat ) = each ( $queue ) ) {
			$query .= " or catid = $cat";
		}
		$query = $query . " ) AND published=1 AND approved = 1";
		$db->setQuery ( $query );
		$result = $db->query ();
		$val = mysql_fetch_row ( $result );
		return $val [0];
	} //getNumberOfLinks
	
	// Путь к категории (шото тут не так)
	// boston тут приложился
	function showCategoryPath( $cat ) {
		global $gid, $tgurl;
		$db = & getDBO ();

		$cat = intval ( $cat );
		if ($cat < 1)
			return;
		$parent = 100;
		while ( $parent ) {
			$db->setQuery ( "SELECT * FROM #__true_catg WHERE cid='$cat'" );
			$row = $db->loadAssocList ();
			//print_r($row);
			$parent = $row [0] ['parent'];
			$name = $row [0] ['name'];
			if (empty ( $path )) {
				$path = $name;
			} else {
				$path = $name . ' &raquo; ' . $path;
			}
			$cat = $parent;
		}
		return $path . " ";
		
	} //JTrueGalleryHelper::showCategoryPath
	
	// TODO:
	// поиск опубликованных категорий в меню
	function getReverseItemid() {
		// бля, это надо дерево строить
		// потом вычислять путь наверх до корня
		// и просматривать ID категорий во всей цепочке
		// потом находить для него опубликованный(!!!) menu id
		
		// чот мутно как-то....
	}
	

	
} //JTrueGalleryHelper

// чото я вообще сомневаюсь, что нужен этот handler
// может, действительно, лучше все рапределить по обработчикам роутеров??
// тем более, что в пасвей и тайтл надо грузить имена, а их можно достать
// только из БД, значит, придется повторно выполнять запрос :(
class JTrueGalleryPageHelper
{
	function __construct() {
	
	} //__construct
	
	function &getInstance() {
		static $instance;
		if( !$instance ) {
			$instance = new JTrueGalleryTitleHelper();
		}
		return $instance;
	} //getInstance
	
	function init() {
		
	} //init
	
	function load() {
		// avoiding call during AJAX because here comes
		// the load limitation when using JApplication
		if( !TG_AJAX ) {
			$view = getUrlParam( 'view' );
			$task = getUrlParam( 'task' );
			
			$pagetitle	= '';
			$pathway	= '';
			
			switch($view) {
				default: break;
			}
			
			$app = &JTuneConfig::getApplication();
			$app->setPageTitle( $pagetitle );
			$app->appendPathway( $pathway );
		}
	} //load
	
	function setPageTitle( $text='' ) {
		$app = &JTuneConfig::getApplication();
		$app->setPageTitle( $text );
	} //setPageTitle
	
	function appendPathway( $text='' ) {
		$app = &JTuneConfig::getApplication();
		$app->appendPathway( $text );
	} //appendPathway
	
	function setPageData( $title='', $pathway='' ){
		$app = &JTuneConfig::getApplication();
		$app->setPageTitle( $title );
		$app->appendPathway( $pathway );
	} //setPageData
}



class TGPicture extends JTrueGalleryPicture{}
class TGCategory extends JTrueGalleryCategory{}
class TGHelper extends JTrueGalleryHelper{}
class TGImagesHelper extends JTrueGalleryImagesHelper{}
class TGPageHelper extends JTrueGalleryPageHelper{}



?>